<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>订单历史 - 币胜客pro</title>
    <link rel="stylesheet" href="styles.css" />
    <style>
      body {
        min-height: 100vh;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        margin: 0;
        padding: 20px;
      }
      
      .back-btn {
        position: fixed;
        top: 20px;
        left: 20px;
        background: rgba(255, 255, 255, 0.2);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;
        padding: 12px 20px;
        border-radius: 50px;
        text-decoration: none;
        font-weight: 500;
        transition: all 0.3s ease;
        z-index: 1000;
      }
      
      .back-btn:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: translateY(-2px);
      }
      
      .order-container {
        min-height: 100vh;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 20px;
      }
      
      .order-content-wrapper {
        margin-top: 80px;
      }
      
      .order-header {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        border: 1px solid rgba(255, 255, 255, 0.2);
      }
      
      .order-title {
        font-size: 2.5rem;
        font-weight: 700;
        color: white;
        margin: 0 0 10px 0;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
      }
      
      .order-subtitle {
        font-size: 1.1rem;
        color: rgba(255, 255, 255, 0.8);
        margin: 0;
      }
      
      .order-content {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        margin-bottom: 30px;
      }
      
      .order-section {
        max-width: 1200px;
        width: 100%;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
      }
      
      .section-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #0f172a;
        margin: 0 0 20px 0;
        display: flex;
        align-items: center;
        gap: 10px;
      }
      
      .section-icon {
        font-size: 1.2rem;
      }
      
      .controls-section {
        margin-bottom: 20px;
        padding: 20px;
        background: #f8fafc;
        border-radius: 10px;
        border: 1px solid #e2e8f0;
      }
      
      .search-filters {
        display: flex;
        flex-direction: column;
        gap: 15px;
      }
      
      .filter-group {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
      }
      
      .filter-input, .filter-select {
        padding: 8px 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        font-size: 14px;
        min-width: 150px;
        background: white;
      }
      
      .filter-input:focus, .filter-select:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }
      
      .filter-actions {
        display: flex;
        gap: 10px;
      }
      
      .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
      }
      
      .btn-primary {
        background: #3b82f6;
        color: white;
      }
      
      .btn-primary:hover {
        background: #2563eb;
      }
      
      .btn-secondary {
        background: #6b7280;
        color: white;
      }
      
      .btn-secondary:hover {
        background: #4b5563;
      }
      
      .btn-sm {
        padding: 6px 12px;
        font-size: 12px;
      }
      
      .btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
      
      .sort-indicator {
        font-size: 12px;
        color: #6b7280;
        margin-left: 5px;
      }
      
      .sort-indicator.active {
        color: #3b82f6;
      }
      
      .pagination-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20px;
        padding: 15px 0;
        border-top: 1px solid #e2e8f0;
      }
      
      .pagination-info {
        color: #6b7280;
        font-size: 14px;
      }
      
      .pagination-controls {
        display: flex;
        align-items: center;
        gap: 10px;
      }
      
      .page-numbers {
        display: flex;
        gap: 5px;
      }
      
      .page-number {
        padding: 6px 10px;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        font-size: 12px;
        cursor: pointer;
        background: white;
      }
      
      .page-number:hover {
        background: #f3f4f6;
      }
      
      .page-number.active {
        background: #3b82f6;
        color: white;
        border-color: #3b82f6;
      }
      
      .status {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 500;
      }
      
      .status-success {
        background: #dcfce7;
        color: #166534;
      }
      
      .status-error {
        background: #fee2e2;
        color: #dc2626;
      }
      
      .status-pending {
        background: #fef3c7;
        color: #d97706;
      }
      
      .page-wrap {
        width: 100%;
        background: transparent;
        border-radius: 0;
        padding: 0;
        box-shadow: none;
        display: flex;
        flex-direction: column;
        gap: 0;
      }
      .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .page-title {
        margin: 0;
        font-size: 24px;
        font-weight: 700;
        color: #0f172a;
      }
      .page-subtitle {
        margin: 4px 0 0;
        color: #475569;
        font-size: 14px;
      }
      .link-btn {
        border: none;
        background: none;
        color: #0ea5e9;
        cursor: pointer;
        font-size: 14px;
        padding: 4px 8px;
      }
      .table-wrap {
        background: transparent;
        border-radius: 0;
        padding: 0;
        box-shadow: none;
        max-height: 70vh;
        overflow: auto;
      }
      table {
        width: 100%;
        border-collapse: collapse;
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        overflow: hidden;
      }
      th, td {
        padding: 12px 16px;
        text-align: left;
        border-bottom: 1px solid #e2e8f0;
        font-size: 14px;
      }
      th {
        background: #f8fafc;
        color: #0f172a;
        font-weight: 600;
        border-bottom: 2px solid #e2e8f0;
      }
      tr:hover td {
        background: #f8fafc;
      }
      tr:last-child td {
        border-bottom: none;
      }
      .form-msg {
        font-size: 13px;
        color: #0ea5e9;
      }
      @media (max-width: 720px) {
        .page-wrap { padding: 24px; }
        th, td { white-space: nowrap; }
      }
    </style>
  </head>
  <body>
    <a href="admin.html" class="back-btn">← 返回管理台</a>
    
    <div class="order-container">
      <div class="order-content-wrapper">
        <!-- 页面头部 -->
        <div class="order-header">
          <h1 class="order-title">📋 订单历史</h1>
          <p class="order-subtitle">查看最近的交易订单记录</p>
        </div>
        
        <!-- 主要内容区域 -->
        <div class="order-content">
          <div class="order-section">
            <h2 class="section-title">
              <span class="section-icon">📊</span>
              订单列表
            </h2>

      <div class="form-msg" id="info-msg" aria-live="polite"></div>
            
            <!-- 搜索和过滤控件 -->
            <div class="controls-section">
              <div class="search-filters">
                <div class="filter-group">
                  <input type="text" id="search-account" placeholder="按账户搜索..." class="filter-input">
                  <input type="text" id="search-exchange" placeholder="按交易所搜索..." class="filter-input">
                  <input type="text" id="search-symbol" placeholder="按交易对搜索..." class="filter-input">
                </div>
                <div class="filter-group">
                  <select id="filter-status" class="filter-select">
                    <option value="">所有状态</option>
                    <option value="sent">已发送</option>
                    <option value="error">错误</option>
                  </select>
                  <select id="filter-side" class="filter-select">
                    <option value="">所有方向</option>
                    <option value="BUY">买入</option>
                    <option value="SELL">卖出</option>
                  </select>
                  <select id="filter-order-type" class="filter-select">
                    <option value="">所有类型</option>
                    <option value="MARKET">市价单</option>
                    <option value="LIMIT">限价单</option>
                  </select>
                </div>
                <div class="filter-actions">
                  <button id="btn-search" class="btn btn-primary">搜索</button>
                  <button id="btn-clear" class="btn btn-secondary">清除</button>
                  <button id="btn-refresh" class="btn btn-secondary">刷新</button>
                </div>
              </div>
            </div>

      <div class="table-wrap">
        <table>
          <thead>
            <tr>
                    <th data-sort="created_at">时间 <span class="sort-indicator">↕</span></th>
              <th>账户</th>
                    <th>信号名称</th>
              <th>交易所</th>
                    <th>交易对</th>
              <th>方向</th>
                    <th>订单类型</th>
                    <th data-sort="qty">数量 <span class="sort-indicator">↕</span></th>
                    <th data-sort="price">价格 <span class="sort-indicator">↕</span></th>
                    <th>交易参考</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody id="orders-history-body">
            <tr><td colspan="11">加载中...</td></tr>
          </tbody>
        </table>
      </div>
            
            <!-- 分页控件 -->
            <div class="pagination-section">
              <div class="pagination-info">
                <span id="pagination-info">显示 0-0 条，共 0 条</span>
              </div>
              <div class="pagination-controls">
                <button id="btn-first-page" class="btn btn-sm btn-secondary" disabled>首页</button>
                <button id="btn-prev-page" class="btn btn-sm btn-secondary" disabled>上一页</button>
                <span id="page-numbers" class="page-numbers"></span>
                <button id="btn-next-page" class="btn btn-sm btn-secondary" disabled>下一页</button>
                <button id="btn-last-page" class="btn btn-sm btn-secondary" disabled>末页</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script>
      (function () {
        'use strict';

        var API_BASE = 'http://43.153.150.144:8080';

        function getToken() {
          try { return localStorage.getItem('token') || ''; } catch (_) { return ''; }
        }

        async function request(path) {
          var headers = { 'Content-Type': 'application/json' };
          var token = getToken();
          if (token) headers.Authorization = 'Bearer ' + token;
          return fetch(API_BASE + path, { method: 'GET', headers: headers });
        }

        var msg = document.getElementById('info-msg');
        var tbody = document.getElementById('orders-history-body');
        
        // 状态管理
        var orderState = {
          currentPage: 1,
          pageSize: 10,
          totalPages: 0,
          totalItems: 0,
          sortBy: 'created_at',
          sortOrder: 'desc',
          filters: {
            account: '',
            exchange: '',
            symbol: '',
            status: '',
            side: '',
            orderType: ''
          },
          allOrders: [],
          filteredOrders: []
        };

        function setMessage(text, tone) {
          msg.textContent = text || '';
          msg.className = 'form-msg';
          if (tone === 'error') {
            msg.style.color = '#dc2626';
          } else {
            msg.style.color = '#0ea5e9';
          }
        }

        setMessage('加载订单数据中...', 'info');
        
        // 初始化事件监听器
        initEventListeners();
        
        // 加载订单数据
        loadOrders();

        // 返回按钮事件已在HTML中通过href处理
        function initEventListeners() {
          // 搜索按钮
          document.getElementById('btn-search').addEventListener('click', function() {
            applyFilters();
          });
          
          // 清除按钮
          document.getElementById('btn-clear').addEventListener('click', function() {
            clearFilters();
          });
          
          // 刷新按钮
          document.getElementById('btn-refresh').addEventListener('click', function() {
            loadOrders();
          });
          
          // 分页按钮
          document.getElementById('btn-first-page').addEventListener('click', function() {
            goToPage(1);
          });
          
          document.getElementById('btn-prev-page').addEventListener('click', function() {
            goToPage(orderState.currentPage - 1);
          });
          
          document.getElementById('btn-next-page').addEventListener('click', function() {
            goToPage(orderState.currentPage + 1);
          });
          
          document.getElementById('btn-last-page').addEventListener('click', function() {
            goToPage(orderState.totalPages);
          });
          
          // 排序点击事件
          document.querySelectorAll('th[data-sort]').forEach(function(th) {
            th.addEventListener('click', function() {
              var sortField = this.getAttribute('data-sort');
              toggleSort(sortField);
            });
          });
          
          // 回车键搜索
          document.querySelectorAll('.filter-input').forEach(function(input) {
            input.addEventListener('keypress', function(e) {
              if (e.key === 'Enter') {
                applyFilters();
              }
            });
          });
        }
        
        // 应用过滤器
        function applyFilters() {
          orderState.filters.account = document.getElementById('search-account').value;
          orderState.filters.exchange = document.getElementById('search-exchange').value;
          orderState.filters.symbol = document.getElementById('search-symbol').value;
          orderState.filters.status = document.getElementById('filter-status').value;
          orderState.filters.side = document.getElementById('filter-side').value;
          orderState.filters.orderType = document.getElementById('filter-order-type').value;
          
          filterAndSortOrders();
        }
        
        // 清除过滤器
        function clearFilters() {
          document.getElementById('search-account').value = '';
          document.getElementById('search-exchange').value = '';
          document.getElementById('search-symbol').value = '';
          document.getElementById('filter-status').value = '';
          document.getElementById('filter-side').value = '';
          document.getElementById('filter-order-type').value = '';
          
          orderState.filters = {
            account: '',
            exchange: '',
            symbol: '',
            status: '',
            side: '',
            orderType: ''
          };
          
          filterAndSortOrders();
        }
        
        // 过滤和排序订单
        function filterAndSortOrders() {
          var filtered = orderState.allOrders.filter(function(order) {
            return (!orderState.filters.account || order.account_name.toLowerCase().includes(orderState.filters.account.toLowerCase())) &&
                   (!orderState.filters.exchange || order.connector.toLowerCase().includes(orderState.filters.exchange.toLowerCase())) &&
                   (!orderState.filters.symbol || order.symbol.toLowerCase().includes(orderState.filters.symbol.toLowerCase())) &&
                   (!orderState.filters.status || order.status === orderState.filters.status) &&
                   (!orderState.filters.side || order.side === orderState.filters.side) &&
                   (!orderState.filters.orderType || order.order_type === orderState.filters.orderType);
          });
          
          // 排序
          filtered.sort(function(a, b) {
            var aVal = a[orderState.sortBy];
            var bVal = b[orderState.sortBy];
            
            if (orderState.sortBy === 'created_at') {
              aVal = new Date(aVal);
              bVal = new Date(bVal);
            }
            
            if (orderState.sortOrder === 'asc') {
              return aVal > bVal ? 1 : -1;
            } else {
              return aVal < bVal ? 1 : -1;
            }
          });
          
          orderState.filteredOrders = filtered;
          orderState.totalItems = filtered.length;
          orderState.totalPages = Math.ceil(filtered.length / orderState.pageSize);
          orderState.currentPage = 1;
          
          renderCurrentPage();
          updatePagination();
        }
        
        // 切换排序
        function toggleSort(field) {
          if (orderState.sortBy === field) {
            orderState.sortOrder = orderState.sortOrder === 'asc' ? 'desc' : 'asc';
          } else {
            orderState.sortBy = field;
            orderState.sortOrder = 'desc';
          }
          
          // 更新排序指示器
          document.querySelectorAll('.sort-indicator').forEach(function(indicator) {
            indicator.textContent = '↕';
            indicator.classList.remove('active');
          });
          
          var currentIndicator = document.querySelector('th[data-sort="' + field + '"] .sort-indicator');
          if (currentIndicator) {
            currentIndicator.textContent = orderState.sortOrder === 'asc' ? '↑' : '↓';
            currentIndicator.classList.add('active');
          }
          
          filterAndSortOrders();
        }
        
        // 跳转到指定页面
        function goToPage(page) {
          if (page >= 1 && page <= orderState.totalPages) {
            orderState.currentPage = page;
            renderCurrentPage();
            updatePagination();
          }
        }
        
        // 渲染当前页
        function renderCurrentPage() {
          var startIndex = (orderState.currentPage - 1) * orderState.pageSize;
          var endIndex = startIndex + orderState.pageSize;
          var pageData = orderState.filteredOrders.slice(startIndex, endIndex);
          
          renderTable(pageData);
          updatePaginationInfo();
        }
        
        // 更新分页信息
        function updatePaginationInfo() {
          var startIndex = (orderState.currentPage - 1) * orderState.pageSize + 1;
          var endIndex = Math.min(orderState.currentPage * orderState.pageSize, orderState.totalItems);
          
          document.getElementById('pagination-info').textContent = 
            '显示 ' + startIndex + '-' + endIndex + ' 条，共 ' + orderState.totalItems + ' 条';
        }
        
        // 更新分页控件
        function updatePagination() {
          var firstBtn = document.getElementById('btn-first-page');
          var prevBtn = document.getElementById('btn-prev-page');
          var nextBtn = document.getElementById('btn-next-page');
          var lastBtn = document.getElementById('btn-last-page');
          
          firstBtn.disabled = orderState.currentPage === 1;
          prevBtn.disabled = orderState.currentPage === 1;
          nextBtn.disabled = orderState.currentPage === orderState.totalPages;
          lastBtn.disabled = orderState.currentPage === orderState.totalPages;
          
          // 生成页码
          var pageNumbers = document.getElementById('page-numbers');
          pageNumbers.innerHTML = '';
          
          var startPage = Math.max(1, orderState.currentPage - 2);
          var endPage = Math.min(orderState.totalPages, orderState.currentPage + 2);
          
          for (var i = startPage; i <= endPage; i++) {
            var pageBtn = document.createElement('span');
            pageBtn.className = 'page-number' + (i === orderState.currentPage ? ' active' : '');
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', function(page) {
              return function() { goToPage(page); };
            }(i));
            pageNumbers.appendChild(pageBtn);
          }
        }

        async function loadOrders() {
          try {
            var res = await request('/orders/admin/recent');
            var data = await res.json();
            
            if (!res.ok) {
              throw new Error((data && data.message) || (data && data.detail) || ('HTTP ' + res.status));
            }
            
            // 处理分页数据结构
            var orders = [];
            if (Array.isArray(data)) {
              // 如果直接返回数组
              orders = data;
            } else if (data && typeof data === 'object') {
              // 如果返回的是分页对象，尝试获取订单数据
              if (data.items && Array.isArray(data.items)) {
                orders = data.items;
              } else if (data.orders && Array.isArray(data.orders)) {
                orders = data.orders;
              } else if (data.data && Array.isArray(data.data)) {
                orders = data.data;
              } else {
                console.error('无法从API响应中提取订单数据:', data);
                throw new Error('API返回的数据结构无法识别');
              }
            } else {
              throw new Error('API返回的数据格式错误');
            }
            
            orderState.allOrders = orders;
            filterAndSortOrders();
            setMessage('共加载 ' + orders.length + ' 条订单。', 'info');
          } catch (err) {
            console.error('加载订单失败:', err);
            setMessage('加载订单失败：' + (err && err.message ? err.message : '未知错误'), 'error');
            tbody.innerHTML = '<tr><td colspan="11">加载失败</td></tr>';
          }
        }

        function renderTable(list) {
          if (!list.length) {
            tbody.innerHTML = '<tr><td colspan="11">暂无订单</td></tr>';
            return;
          }
          var rows = list.map(function (item) {
            var statusClass = item.status === 'error' ? 'status-error' : 
                             item.status === 'sent' ? 'status-success' : 'status-pending';
            var sideText = item.side === 'BUY' ? '买入' : item.side === 'SELL' ? '卖出' : item.side;
            var orderTypeText = item.order_type === 'MARKET' ? '市价单' : 
                               item.order_type === 'LIMIT' ? '限价单' : item.order_type;
            
            return '<tr>' +
              '<td>' + (item.created_at || '-') + '</td>' +
              '<td>' + (item.account_name || '-') + '</td>' +
              '<td>' + (item.signal_name || '-') + '</td>' +
              '<td>' + (item.connector || '-') + '</td>' +
              '<td>' + (item.symbol || '-') + '</td>' +
              '<td>' + sideText + '</td>' +
              '<td>' + orderTypeText + '</td>' +
              '<td>' + (item.qty || '-') + '</td>' +
              '<td>' + (item.price || '-') + '</td>' +
              '<td>' + (item.tx_ref || '-') + '</td>' +
              '<td><span class="status ' + statusClass + '">' + (item.status || '-') + '</span></td>' +
            '</tr>';
          }).join('');
          tbody.innerHTML = rows;
        }
      })();
    </script>
  </body>
</html>
